import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useContext } from 'react';
import 'moment/locale/zh-cn';
import { useRouter } from 'next/router';
import { Tree, Radio, Space, Input, Dropdown, Modal, message } from 'antd';
import type { MenuProps } from 'antd';
import type { DataNode } from 'antd/es/tree';
import {
  DownOutlined,
  FrownFilled,
  FrownOutlined,
  MehOutlined,
  SmileOutlined,
  ReloadOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import { WorkbenchesContext, } from '@/components/workbenches/workbenches-context';

import WorkbenchesIcon from '@/components/workbenches/icons';
import { ComponentType, } from '@/components/workbenches/hooks/type';
import { modelDelete, modelGet } from '@/client/api/workbenches';
import { deleteMetricQuery } from '@/client/api/query';
import MyEmpty from '@/components/common/MyEmpty';
const dataTree = () => {
  const { t, i18n } = useTranslation();
  const {
    tabPosition,
    searchValue,
    setSearchValue,
    changeTabPosition,
    treeData,
    treeDataFilter,
    defaultSelectedKeys,
    setDefaultSelectedKeys,
    onSelect,
    addTabs,
    clearChange,
    delTabChange
  } = useContext(WorkbenchesContext);
  const router = useRouter();
  const { DirectoryTree } = Tree;

  const items: MenuProps['items'] = [
    {
      key: '1',
      label: (
        <div className='flex items-center' onClick={() => addTabs({ info: {} }, ComponentType.MODEL)}>
          <WorkbenchesIcon type='模型' styClass='!mx-1' />
          <div>{t('w_model')}</div>
        </div>
      ),
    },
    {
      key: '2',
      label: (
        <div className='flex items-center' onClick={() => addTabs({ info: {} }, ComponentType.QUERY)}>
          <WorkbenchesIcon type='查询' styClass='!mx-1' />
          <div>{t('w_query')}</div>
        </div>
      ),
    },
  ];

  const [contextMenu, setContextMenu] = useState<{ visible: boolean; x: number; y: number; node: any }>({
    visible: false,
    x: 0,
    y: 0,
    node: null,
  });

  const handleRightClick = async ({ event, node }: { event: React.MouseEvent; node: any }) => {
    event.preventDefault();
    if (!['Model', 'Query'].includes(node.nodeType)) return;
    setContextMenu({
      visible: true,
      x: event.clientX,
      y: event.clientY,
      node,
    });
  };
  const delModel = async (id: string) => {
    const { data }: any = await modelGet({ id });
    if (data?.code != 0 || !data.data) {
      return message.error(data?.msg || '查询失败!')
    }
    if (!!data.data?.status) {
      return message.error('该模型已发布，请先下线再删除!')
    }
    modelDelete({ id }).then((res => {
      if (res.data.code == 0) {
        setContextMenu({ ...contextMenu, visible: false });
        delTabChange({ key: contextMenu.node.key });
        message.success(res.data.msg || `操作成功!`);
      } else {
        message.error(res.data.msg || `操作失败!`);
      }
    }));
  }
  const delQuery = async (id: string) => {
    deleteMetricQuery({ id }).then((res => {
      if (res.data.code == 0) {
        delTabChange({ key: contextMenu.node.key });
        message.success(res.data.msg || `操作成功!`);
      } else {
        message.error(res.data.msg || `操作失败!`);
      }
    }));
  }
  const handleMenuClick: MenuProps['onClick'] = ({ key }) => {
    if (key === 'delete') {

      Modal.confirm({
        title: '确认删除',
        content: '确认删除，是否继续？',
        okText: '确认',
        cancelText: '取消',
        onOk: async () => {
          if (!contextMenu?.node?.id) return
          const id = contextMenu.node.id.split('_')[1];
          if (contextMenu.node?.nodeType == 'Model') {
            delModel(id);
          }
          if (contextMenu.node?.nodeType == 'Query') {
            delQuery(id);
          }
        }
      });
      console.log('Delete node:', contextMenu.node);
    }
  };

  const menuItems: MenuProps['items'] = [
    { key: 'delete', label: t('删除') },
  ];
  useEffect(() => {
    const handleClickOutside = () => {
      setContextMenu((prev) => ({ ...prev, visible: false }));
    };

    document.addEventListener('click', handleClickOutside);
    return () => {
      document.removeEventListener('click', handleClickOutside);
    };
  }, []);

  return (
    <div
      className='w-1/6 h-full border-r border-borderColor dark:border-darkBorderColor p-3'
      onClick={() => setContextMenu({ ...contextMenu, visible: false })}
    >
      <Space style={{ marginBottom: 10 }}>
        <Input value={searchValue} onChange={(e) => setSearchValue(e.target.value)} placeholder="搜索" />
        <ReloadOutlined onClick={() => {
          clearChange()
        }} className='cursor-pointer' />
        <Dropdown menu={{ items }}>
          <PlusOutlined className='cursor-pointer' />
        </Dropdown>
      </Space>
      <Space style={{ marginBottom: 10 }}>
        <Radio.Group value={tabPosition} onChange={changeTabPosition}>
          <Radio.Button value="all">{t('w_all')}</Radio.Button>
          <Radio.Button value="data">{t('w_data')}</Radio.Button>
          <Radio.Button value="model">{t('w_model')}</Radio.Button>
          <Radio.Button value="query">{t('w_query')}</Radio.Button>
        </Radio.Group>
      </Space>

      {treeDataFilter?.length == 0 ?
        <MyEmpty description='暂无数据' /> :
        <Tree
          className='w-full bg-[#f7f7f7] dark:bg-[#151622] overflow-y-auto'
          style={{ height: 'calc(100vh - 110px)' }}
          showIcon
          defaultSelectedKeys={defaultSelectedKeys}
          switcherIcon={<DownOutlined />}
          treeData={treeDataFilter}        
          onSelect={onSelect}
          onRightClick={handleRightClick}
        />
      }
      {contextMenu.visible && (
        <Dropdown
          menu={{ items: menuItems, onClick: handleMenuClick }}
          open
          trigger={['contextMenu']}
          overlayStyle={{ position: 'fixed', left: contextMenu.x, top: contextMenu.y }}
        />
      )}
    </div>
  );
}

export default dataTree;
